//
//  Delay.swift
//  MECollege
//
//  Created by 马康旭 on 2017/7/11.
//  Copyright © 2017年 马康旭. All rights reserved.
//

import Foundation

//MARK:- 给予GCD写一个可以取消的延时任务
typealias Task = (_ cancel: Bool) -> Void


func delay(_ time: TimeInterval, task: @escaping () -> ()) -> Task?{
    
    func dispatch_later(block: @escaping () -> ()){
        
        let t = DispatchTime.now() + time
        
        DispatchQueue.main.asyncAfter(deadline: t, execute: block)
    }
    
    var closure:(() -> ())? = task
    var result: Task?
    
    let delayClosure: Task = {
        
        cancel in
        
        if let internalClosure = closure {
            
            if cancel == false {
                
                DispatchQueue.main.async(execute: internalClosure)
            }
        }
        
        closure = nil
        result = nil
        
        print("closure become nil")
    }
    
    result = delayClosure
    
    dispatch_later {
        
        if let delayedClosure = result{
            
            delayedClosure(false)
        }
    }
    
    return result
}

func cancle(_ task: Task?){
    
    task?(true)
}
